<script setup>
import {ajax, getToken} from 'framework'
import axios from 'axios'
import {ref,onMounted} from 'vue'
import {message, modal} from 'heyui'
import JsonInput from "../../comp/JsonInput.vue";
import PasswordInput from "../PasswordInput.vue";
import {useRouter} from 'vue-router'

const router = useRouter()
const ds = ref()
const showData = ref(false)
const dbData = ref({})
const sqlDrivers=["com.mysql.jdbc.Driver","org.postgresql.Driver","com.microsoft.sqlserver.jdbc.SQLServerDriver","oracle.jdbc.driver.OracleDriver"]
function viewData(data) {
  axios({
    url: 'developer/resource/file/' + data.id,
    method: 'get',
    headers: {
      "Magic-Token": getToken()
    }
  }).then(r => {
    dbData.value = r.data
    if (r.data.properties) {
      r.data.properties = JSON.stringify(r.data.properties, null, 2)
    }
    showData.value = true
  })
}

function getData() {
  let v = dbData.value
  if(v.properties==null){
    v.properties="{}"
  }
  let properties=''
  try{
    properties = JSON.parse(v.properties)
  }catch (e){
    message("配置格式错误："+e)
    throw e;
  }
  return {
    createBy: v.createBy,
    createTime: v.createTime,
    driverClassName: v.driverClassName,
    groupId: v.groupId,
    id: v.id,
    key: v.key,
    lock: v.lock,
    maxRows: v.maxRows,
    name: v.name,
    password: v.password,
    properties: properties,
    type: v.type,
    updateBy: v.updateBy,
    updateTime: v.updateTime,
    url: v.url,
    username: v.username
  }
}

function test() {
  axios({
    url: 'developer/datasource/jdbc/test',
    method: 'post',
    headers: {
      "Magic-Token": getToken()
    },
    data: getData()
  }).then(r => {
    if (r.data == 'ok') {
      message('连接成功')
    } else {
      modal({
        title: '连接失败',
        content: r.data
      });
    }
  })
}

function save() {
  axios({
    url: 'developer/resource/file/datasource/save',
    method: 'post',
    headers: {
      "Magic-Token": getToken()
    },
    data: getData()
  }).then(r => {
    if (r.code == 1) {
      message('已保存')
      showData.value = false
      ds.value.load()
    } else {
      modal({
        title: '保存失败',
        content: r.message
      });
    }
  })
}

function changeLock(v) {
  let url = v.lock == '1' ? 'developer/resource/unlock' : 'developer/resource/lock'
  let data=new FormData()
  data.append('id', v.id)
  axios({
    url,
    method: 'post',
    headers: {
      "Magic-Token": getToken()
    },
    data: data
  }).then(r => {
    if (r.code == 1) {
      message(`已${v.lock == '1' ? '解锁' : '锁定'}该数据库连接`)
      ds.value.load()
    } else {
      modal({
        title: `${v.lock == '1' ? '解锁' : '锁定'}失败`,
        content: r.message
      });
    }
  })
}
function deleteData(d){
  let url = 'developer/resource/delete'
  let data=new FormData()
  data.append('id', v.id)
  axios({
    url,
    method: 'post',
    headers: {
      "Magic-Token": getToken()
    },
    data: data
  }).then(r => {
    if (r.code == 1) {
      ds.value.load()
    } else {
      modal({
        title: `连接删除失败`,
        content: r.message
      });
    }
  })
}
function create(){
  dbData.value={
    groupId:"datasource:0",
    maxRows:-1,
    type:'cn.beecp.BeeDataSource'
  }
  showData.value=true
}
function showLink(data){
  router.push({
    hash:"#editor",
    query:{
      id:data.id
    }
  })
}
</script>
<template>
  <DataTable url="db/all" method="get" ref="ds">
    <template #tools>
      <Button color="primary" @click="create">创建</Button>
    </template>
    <template #default="table">
      <Table :datas="table.data">
        <TableItem title="Key" prop="key"></TableItem>
        <TableItem title="名称" prop="name"></TableItem>
        <TableItem title="操作" :width="200">
          <template #default="{data}">
            <span style="padding-right: 10px"><i class="link icon-link" @click="showLink(data)">连接</i></span>

            <span v-if="data.id">

              <i class="link jeicon-edit" @click="viewData(data)">修改</i>
              <Poptip :content="data.lock=='1'?'解锁该数据库连接？':'锁定该数据库连接？'" @confirm="changeLock(data)">
                <i :class="data.lock == '1' ? 'icon-unlock link':'icon-lock link'"
                   style="font-size: 16px;padding-left: 10px;">{{ data.lock == '1' ? '解锁' : '锁定' }}</i>
              </Poptip>
                <Poptip v-if="data.lock=='0'" content="删除该该数据库连接？" @confirm="deleteData(data)">
                  <i class="link icon-trash">删除</i>
                </Poptip>
            </span>
          </template>
        </TableItem>
      </Table>
    </template>
  </DataTable>
  <Modal v-model="showData" :closeOnMask="false" hasDivider hasCloseIcon>
    <template #header>
      {{dbData.id?'修改':'创建'}}数据库连接
    </template>
    <Form :model="dbData" mode="twocolumn">
      <FormItem label="名称" prop="name">
        <Input v-model="dbData.name"/>
      </FormItem>
      <FormItem label="Key" prop="key">
        <Input v-model="dbData.key"/>
      </FormItem>
      <FormItem label="驱动类" prop="driverClassName">
        <AutoComplete
            v-model="dbData.driverClassName"
            :datas="sqlDrivers"
            type="object"
            :must-match="false"
        />
      </FormItem>
      <FormItem label="URL" prop="url" single>
        <Input v-model="dbData.url"/>
      </FormItem>
      <FormItem label="用户名" prop="username">
        <Input v-model="dbData.username"/>
      </FormItem>
      <FormItem label="密码" prop="password">
        <PasswordInput v-model="dbData.password"/>
      </FormItem>

      <FormItem label="数据源类型" prop="type">
        <Input v-model="dbData.type"/>
      </FormItem>
      <FormItem label="maxRows" prop="maxRows">
        <NumberInput v-model="dbData.maxRows"/>
      </FormItem>
      <FormItem label="其他配置" prop="properties" single>
        <JsonInput style="height: 200px" v-model="dbData.properties"/>
      </FormItem>
    </Form>
    <template #footer>
      <Button @click="showData=false">取消</Button>
      <Button color="green" @click="test">测试连接</Button>
      <Button color="primary" @click="save">{{dbData.id?'修改':'保存'}}</Button>
    </template>
  </Modal>
</template>
